#include<mysql/mysql.h>
#include<iostream>
using namespace std;

int main()
{
    //初始化句柄
    MYSQL *mysql=mysql_init(NULL);
    if(mysql==NULL)//初始化失败
    {
        cout<<"mysql_init failed!!!"<<endl;
        return -1;
    }
    //连接服务器
    if(mysql_real_connect(mysql,"127.0.0.1","root","","db_IM",0,NULL,0)==nullptr)
    {
        cout<<"connect server failed:"<<mysql_error(mysql)<<endl;
        mysql_close(mysql);//释放操作句柄
        return -1;
    }
    //设置字符集
    mysql_set_character_set(mysql,"utf8");
    //选择数据库
    mysql_select_db(mysql,"db_IM");
    //执行语句
    //const char *sql="insert into tbstu values(null,'张三',20,30,50,now());";
    const char *sql="select*from tbstu;";
    int ret=mysql_query(mysql,sql);//使用句柄操作数据库
    if(ret!=0)
    {
        cout<<"query failed:"<<mysql_error(mysql)<<endl;
        mysql_close(mysql);//释放操作句柄
        return -1;
    }

    //保存结果集到本地
    MYSQL_RES *res=mysql_store_result(mysql);
    if(res==nullptr)
    {
        cout<<"store_result failed:"<<mysql_error(mysql)<<endl;
        return -1;
    }
    //获取结果集中的条数和列数
    int num_row=mysql_num_rows(res);
    int num_col=mysql_num_fields(res);
    //根据条数和列数，遍历结果集
    for(int i=0;i<num_row;i++)
    {
        MYSQL_ROW row=mysql_fetch_row(res);//按行取出数据
        for(int j=0;j<num_col;j++)//按列打印数据
        {
            printf("%s\t",row[j]);
        }
        cout<<endl;
    }
    //释放结果集
    mysql_free_result(res);
    //关闭操作句柄
    mysql_close(mysql);
    return 0;
}